local args = ngx.req.get_uri_args()

local act_id=args.act_id

local json = require "cjson"

if nil == act_id then
    ngx.say('{"code":10000, "message":"act_id不能为空", "data":{"allowed": false, "type":"can-not-found"}}');
    return
end

local vote_token = args.vote_token

if nil == vote_token then
    ngx.say('{"code":200,"message":"vote_token 不能为空","data":""}')
    return
end

local prize_rule = "rules:"..act_id
local redis_client = require "lib.redis"
local redis = redis_client:new()

-- local codes, err = redis:get(guess_code)
local rules, err = redis:hmget('rules:'..act_id, 'limit_type', 'limit_times', 'start_at', 'end_at', 'is_paused')

if err ~= nil then
    ngx.say('{"code":500,"message":"redis 服务出错","data":"code_rule"}')
    return
end

if nil == rules then
    ngx.say('{"code":10000,"message":"活动不存在","data":""}')
    return
end

local is_paused = tonumber(rules[5])
--验证活动是否暂停
if is_paused == 1 then
    ngx.say('{"code":10000,"message":"活动已暂停","data":{"allowed":false,"type":"paused","surplus_times":0}}')
    return
end

local time = ngx.time()
local start_at = rules[3] or 0
local end_at = rules[4] or (time + 1)

if time < tonumber(end_at) then
    ngx.say('{"code":10000,"message":"活动已结束","data":""}')
    return
end

if time<tonumber(start_at) then
    ngx.say('{"code":10000,"message":"活动还未开始","data":""}')
    return
end

local uid = args.uid

if nil == uid then
    ngx.say('{"code":10000,"message":"你还未登录","data":""}')
    return
end

local user, err = redis:hget('app:uid'..act_id,user_id)
--验证登陆
if vote_token ~= user then
    ngx.say('{"code":10000,"message":"验签不匹配"}');
    return
end

local ways = args.ways
--删除验签
if ways ~= "wechat" then
    redis:hset("app:uid"..act_id,user_id,'')
end

local times_key = "times:"..act_id..":"..user_id
local mode = rules[1]
local limit_times = tonumber(rules[2])
local surplus_times  = 0

if mode == "day" then
    local times_or_everyday = redis:hget(times_key,ngx.today());
    local t = tonumber(times_or_everyday) or 0
    surplus_times = limit_times - t
    if t>= limit_times then
        ngx.say('{"code":10000,"message":"","data":{"allowed":false,"type":"no-times","surplus_times":' , surplus_times, '}}')
        return
    end
else
    local times_of_life = redis:hget(times_key, 'total')
    local t = tonumber(times_of_life) or 0
    surplus_times = limit_times - t
    if t >= limit_times then
        ngx.say('{"code":10000,"message":"您的抽奖次数已用完","data":{"allowed":false,"type":"no-times","surplus_times":', surplus_times, '}}')
        return
    end
end

ngx.say('{"code":200,"message":"success","data":{"allowed":true,"type":null,"surplus_times":', surplus_times, '}}')

